<template>
  <div class="llmView">
    <!-- <input v-model="inputText" placeholder="Enter text" />
      <button @click="quickChat()">Send to AI</button>
      <p>Response from Coze AI: {{ response }}</p> -->
    <div class="content">
      <!-- top -->
      <div class="searchContent">
        <div class="title">基于LLM的智能聊天室</div>
        <div class="inputContent">
          <el-input
            size="big"
            v-model="searchContent"
            placeholder="search"
            @focus="handleFocus"
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
      </div>
      <!-- bottom -->
      <div class="chatContent">
        <div class="chatBox">
          <!-- 右侧 -->
          <div
            class="paragraphBox"
            v-for="(item, index) in chatList"
            :key="index"
          >
            <!-- 头像 -->
            <div class="userPic" v-if="item.isAi">
              <img :src="item.img" alt="" />
            </div>
            <!-- 详情 -->
            <div
              class="detailsBox"
              :style="`${
                item.isAi
                  ? 'align-items: flex-start;margin-left: 1vh;margin-right: 0vh;'
                  : 'align-items: flex-end;margin-right: 1vh;margin-left: 0vh;'
              }`"
            >
              <!-- name -->
              <div class="userName">{{ item.name }}</div>
              <!-- chat -->
              <div
                class="userSay"
                :style="`${
                  item.isAi ? 'background:#fff;' : 'background:#95EC69'
                }`"
              >
                {{ item.content }}
              </div>
            </div>
            <!-- 头像 -->
            <div class="userPic" v-if="!item.isAi">
              <img :src="item.img" alt="" />
            </div>
          </div>
        </div>
        <div class="line"></div>
        <div class="sendBox">
          <div class="textInput">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="Enter your chat content..."
              v-model="sendData"
            >
            </el-input>
          </div>
          <div class="enterButton">
            <el-button type="success" round @click="sendMsg()">发送</el-button>
          </div>
        </div>
      </div>
    </div>
    <!-- 弹框组件 -->
    <div class="searchPage" v-if="showSearch">
      <Search @child-method="handleClose" class="searchs"></Search>
    </div>
  </div>
</template>
   
  <script>
import axios from "axios";
import Search from "./components/search.vue";
import { getOnlineInfo } from "../../api/index.js";
import { CozeAPI, ChatEventType } from "@coze/api";

export default {
  components: { Search },
  data() {
    return {
      user: {
        name: "最爱吃芋泥啦",
        userId: "610113xxxxxxxx2921",
        img: require("../../assets/user.png"),
      },
      AiDet: {},
      inputText: "",
      response: "",
      searchContent: "",
      showSearch: false,
      isAi: false,
      chatList: [
        // {
        //   name: "Aiko",
        //   isAi: true,
        //   content:
        //     "  xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        //   img: require("../../assets/Ai.png"),
        // },
      ],
      sendData: "",
    };
  },
  methods: {
    // 对话
    async quickChat() {
      this.response = "";
      // Initialize client with your Personal Access Token
      const client = new CozeAPI({
        token:
          "pat_La8cgWA7YHSzvpfSTPSNFnW7P4mrmPTHZVrXu5Nudp3WDFjhiq4NyZ5m4iGG79jl", // Get your PAT from https://www.coze.com/open/oauth/pats
        // or
        // token: async () => {
        //   // refresh token if expired
        //   return "Bearer pat_La8cgWA7YHSzvpfSTPSNFnW7P4mrmPTHZVrXu5Nudp3WDFjhiq4NyZ5m4iGG79jl";
        // },
        // Authorization:
        //   "Bearer pat_La8cgWA7YHSzvpfSTPSNFnW7P4mrmPTHZVrXu5Nudp3WDFjhiq4NyZ5m4iGG79jl", // 替换为你的API密钥
        // baseURL: "http://api.wlai.vip",
        // baseURL:COZE_COM_BASE_URL,
        baseURL: "https://api.coze.cn",
        allowPersonalAccessTokenInBrowser: true,
      });
      //console.log(client);
      const stream = await client.chat.stream({
        bot_id: "7460766089165864995",
        additional_messages: [
          {
            content: this.inputText,
            content_type: "text",
            role: "user",
          },
        ],
      });
      //console.log(stream);
      for await (const part of stream) {
        if (part.event === ChatEventType.CONVERSATION_MESSAGE_DELTA) {
          //console.log(part.data.content);
          this.response += part.data.content; //实时响应
          // process.stdout.write(part.data.content); // 实时响应
        }
      }
    },
    // 获取智能体配置
    async getRobot() {
      this.chatList = [];
      let params = {
        token:
          "pat_La8cgWA7YHSzvpfSTPSNFnW7P4mrmPTHZVrXu5Nudp3WDFjhiq4NyZ5m4iGG79jl",
        bot_id: "7460766089165864995",
      };
      let data = await getOnlineInfo(params);
      if (data.code == 0) {
        this.AiDet = {
          img: data.data.icon_url,
          name: data.data.name,
          isAi: true,
          content: data.data.onboarding_info.prologue,
          bot_id: data.data.bot_id,
        };
        this.chatList.push({
          img: data.data.icon_url,
          name: data.data.name,
          isAi: true,
          content: data.data.onboarding_info.prologue.replace(
            /\{\{[^}]+\}\}/g,
            this.user.name
          ),
        });
      }
    },
    // search
    handleFocus() {
      this.showSearch = true;
    },
    handleClose() {
      this.showSearch = false;
    },
    // 发送
    async sendMsg() {
      const client = new CozeAPI({
        token:
          "pat_La8cgWA7YHSzvpfSTPSNFnW7P4mrmPTHZVrXu5Nudp3WDFjhiq4NyZ5m4iGG79jl",
        baseURL: "https://api.coze.cn",
        allowPersonalAccessTokenInBrowser: true,
      });
      const stream = await client.chat.stream({
        bot_id: "7460766089165864995",
        additional_messages: [
          {
            content: this.sendData,
            content_type: "text",
            role: "user",
          },
        ],
      });
      this.chatList.push({
        name: this.user.name,
        isAi: false,
        content: this.sendData,
        img: this.user.img,
      });
      this.sendData = "";
      this.chatList.push({
        name: this.AiDet.name,
        isAi: true,
        content: "",
        img: this.AiDet.img,
      });
      for await (const part of stream) {
        if (part.event === ChatEventType.CONVERSATION_MESSAGE_DELTA) {
          this.chatList[this.chatList.length - 1].content += part.data.content; //实时响应
        }
        this.isScroll();
      }
    },
    // 检测是否有滚动条
    hasScroll(e) {
      return e.scrollHeight > e.clientHeight;
    },
    // 检测是否存在滚动条
    isScroll() {
      const container = document.querySelector(".chatBox"); // 替换为你的元素选择器
      if (this.hasScroll(container)) {
        let pageHeight = document.querySelector(".chatBox").clientHeight;
        document
          .querySelector(".chatBox")
          .scrollTo({ top: pageHeight, behavior: "smooth" }); // 平滑滚动到100px的位置
      }
    },
  },
  mounted() {
    // 获取智能体配置
    this.getRobot();
    // 获取页面高度
  },
};
</script>
  <style scoped>
.llmView {
  width: 96vw;
  height: 98vh;
  margin: 0 auto;
  position: relative;
  padding-top: 1vh;
}
.content {
  width: 100%;
  height: 100%;
}
.searchPage {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: #a9a9a9e3;
}
.searchs {
  width: 70vw;
  height: 60vh;
  border-radius: 10px;
  position: absolute;
  background: #fff;
  left: 50%;
  margin-left: -35vw;
  top: 50%;
  margin-top: -30vh;
}
.searchContent {
  width: 100%;
  height: 5vh;
  display: flex;
  justify-content: space-between;
}
.title {
  font-size: 1.5em;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.chatContent {
  width: calc(100% - 2vw);
  height: calc(100% - 10vh);
  margin-top: 1vh;
  border-radius: 10px;
  background: #9997971c;
  padding: 2vh 1vw;
}
.chatBox {
  width: 100%;
  height: calc(100% - 14vh);
  overflow: auto;
  padding-bottom: 1vh;
}
.line {
  width: 100%;
  height: 0;
  border: 1px solid #e4e2e2;
  margin-top: 1.5vh;
}
.paragraphBox {
  width: 100%;
  height: auto;
  display: flex;
  margin-top: 3vh;
}
.paragraphBox:first-of-type {
  margin-top: 0;
}
.userPic {
  width: 5vh;
  height: 5vh;
  border-radius: 50%;
  > img {
    width: 100%;
    height: 100%;
  }
}
.detailsBox {
  width: calc(100% - 6vh);
  height: auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  margin-left: 1vh;
}
.userName {
  font-size: 18px;
}
.userSay {
  width: auto;
  max-width: calc(100% - 5vw);
  height: auto;
  /* border: 1px solid rgba(128, 128, 128, 0.555); */
  padding: 1vh 1vh;
  border-radius: 10px;
  word-wrap: break-word;
  text-align: left;
  margin-top: 1vh;
}
.sendBox {
  width: 100%;
  height: 10vh;
  margin-top: 1.5vh;
  display: flex;
}
.inputContent {
  width: 30%;
  height: 100%;
}
.textInput {
  height: 100%;
  width: calc(100% - 15%);
}
.enterButton {
  height: 100%;
  width: 15%;
  margin-left: 1vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
/deep/ .el-button--small.is-round {
  width: 100%;
  height: 50%;
  font-size: 0.9rem;
}
/deep/ .el-textarea {
  height: 100%;
}
/deep/ .el-textarea__inner {
  height: 100% !important;
}
/deep/ .el-input--small {
  font-size: 1em;
}

</style>